//
//  JHChatListViewController.m
//  JHChat
//
//  Created by JiaHao on 2/22/15.
//  Copyright (c) 2015 JiaHao. All rights reserved.
//

#import "JHChatListViewController.h"
#import "JHChatListCell.h"
#import "XMPPMessageArchiving_Contact_CoreDataObject+RecentContact.h"
#import "JSBadgeView.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "JHChatViewController.h"
#import "HPGrowingTextView.h"
#import "AGEmojiKeyBoardView.h"

@interface JHChatListViewController ()<UITableViewDelegate,UITableViewDataSource,NSFetchedResultsControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) XMPPStream * xmppStream;
@property (nonatomic, strong) NSFetchedResultsController *fetchedRecentResultsController;
@property (nonatomic, assign) NSNumber *totalUnreadMessagesNum;
@property (nonatomic, strong) NSManagedObjectContext *managerObjectContext;
@property (strong,nonatomic) NSMutableArray *chatList;
@end

@implementation JHChatListViewController


-(NSMutableArray *)chatList
{
    if (!_chatList) {
        _chatList = [NSMutableArray new];
    }
    return _chatList;
}

- (NSFetchedResultsController *)fetchedRecentResultsController
{
    if (!_fetchedRecentResultsController) {
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Contact_CoreDataObject"
                                                  inManagedObjectContext:self.managerObjectContext];
        
        NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"mostRecentMessageTimestamp" ascending:NO];
        NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, nil];
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:entity];
        [fetchRequest setSortDescriptors:sortDescriptors];
        
        _fetchedRecentResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                              managedObjectContext:self.managerObjectContext
                                                                                sectionNameKeyPath:nil
                                                                                         cacheName:nil];
        [_fetchedRecentResultsController setDelegate:self];
    }
    
    return _fetchedRecentResultsController;
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    NSLog(@"controllerDidChangeContent");
    [self updateUserDisplayName];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.xmppStream = [JHXMPPManager sharedManager].xmppStream;
    self.managerObjectContext = [[JHXMPPManager sharedManager] managedObjectContext_messageArchiving];
    [self fetchRecentContact];
    self.tableView.tableFooterView = [[UIView alloc] init];

}

- (void)fetchRecentContact
{
    NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"streamBareJidStr = '%@'",
                                                                     [[JHXMPPManager sharedManager] myJID].bare]];
    [self.fetchedRecentResultsController.fetchRequest setPredicate:filterPredicate];
    NSError *error = nil;
    if (![self.fetchedRecentResultsController performFetch:&error]) {
        NSLog(@"Error performing fetch: %@", error);
    }
    else {
        [self updateUserDisplayName];
    }
}

- (void)updateUserDisplayName
{
    NSArray *array = [self.fetchedRecentResultsController fetchedObjects];
    NSInteger totalUnreadCount = 0;
    
    if (array.count > 0) {
        XMPPUserCoreDataStorageObject *rosterUser = nil;
        for (XMPPMessageArchiving_Contact_CoreDataObject *contact in array) {
            
            rosterUser =
            [[JHXMPPManager sharedManager].xmppRosterStorage userForJID:contact.bareJid
                                                           xmppStream:self.xmppStream
                                                 managedObjectContext:[[JHXMPPManager sharedManager]managedObjectContext_roster]];
            
            contact.displayName = rosterUser.displayName;
            contact.unreadMessages = rosterUser.unreadMessages;

            totalUnreadCount = totalUnreadCount + rosterUser.unreadMessages.intValue;
        }
        self.totalUnreadMessagesNum = [NSNumber numberWithInt:totalUnreadCount];
    }
    if (totalUnreadCount > 0) {
        UITabBarItem *item = [self.tabBarController.tabBar.items objectAtIndex:0];
        [item setBadgeValue:[NSString stringWithFormat:@"%ld",(long)totalUnreadCount]];
    }
   
    self.chatList = [NSMutableArray arrayWithArray:array];
    [self.tableView reloadData];
}




-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chatList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JHChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JHChatListCell"];
    XMPPMessageArchiving_Contact_CoreDataObject *contact = [self.chatList objectAtIndex:indexPath.row];

    XMPPUserCoreDataStorageObject *rosterUser =
    [[JHXMPPManager sharedManager].xmppRosterStorage userForJID:contact.bareJid
                                                     xmppStream:self.xmppStream
                                           managedObjectContext:[[JHXMPPManager sharedManager]managedObjectContext_roster]];
    
    if (contact.unreadMessages.integerValue != 0) {
        JSBadgeView *badgeView = [[JSBadgeView alloc] initWithParentView:cell.avatarImageView alignment:JSBadgeViewAlignmentTopRight];
        badgeView.badgeText = [NSString stringWithFormat:@"%@",rosterUser.unreadMessages];
    }
    [cell.avatarImageView setImageWithURL:rosterUser.photo placeholderImage:[UIImage imageNamed:@"head_s"]];
    cell.lastMessageLabel.text = contact.mostRecentMessageBody;
    cell.timeLabel.text = [self stringFromDate:contact.mostRecentMessageTimestamp];
    cell.friendNameLabel.text = contact.displayName;
    return cell;
}

- (NSString *)stringFromDate:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM-dd HH:mm"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    return destDateString;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    JHChatListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    for (UIView *view in cell.avatarImageView.subviews) {
        if ([view isKindOfClass:[JSBadgeView class]]) {
            [view removeFromSuperview];
        }
    }
    XMPPMessageArchiving_Contact_CoreDataObject *contact = [self.chatList objectAtIndex:indexPath.row];
    XMPPUserCoreDataStorageObject *rosterUser =
    [[JHXMPPManager sharedManager].xmppRosterStorage userForJID:contact.bareJid
                                                     xmppStream:self.xmppStream
                                           managedObjectContext:[[JHXMPPManager sharedManager]managedObjectContext_roster]];
    [self refreshTabbbarItemWithIndex:contact.unreadMessages.integerValue];
    contact.unreadMessages = @0;
    
    JHChatViewController *target = [self.storyboard instantiateViewControllerWithIdentifier:@"JHChatViewController"];
    //记录当前聊天的人jid
    [JHXMPPManager sharedManager].currentTalkJid = contact.bareJid;
    target.currentJid = contact.bareJid;
    [self.navigationController pushViewController:target animated:YES];
    
    dispatch_async(dispatch_get_main_queue(), ^{
            rosterUser.unreadMessages = @0;
            NSError *error = nil;
            if (![[JHXMPPManager sharedManager].managedObjectContext_roster save:&error]) {
                NSLog(@"didUpdateObject save error: %@", [error description]);
            }
    });
}



- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        XMPPMessageArchiving_Contact_CoreDataObject *contact = [self.chatList objectAtIndex:indexPath.row];
        [self refreshTabbbarItemWithIndex:contact.unreadMessages.integerValue];
        NSManagedObject *object = [self.fetchedRecentResultsController objectAtIndexPath:indexPath];
        NSManagedObjectContext *context = [self.fetchedRecentResultsController managedObjectContext];
        if (object) {
            [context deleteObject:object];
            NSError *error = nil;
            if (![context save:&error]) {
                NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            }
        }
      
    }
}


-(void)refreshTabbbarItemWithIndex:(NSInteger)index
{
    UITabBarItem *item = [self.tabBarController.tabBar.items objectAtIndex:0];
    NSInteger currentBadge = [[item badgeValue] integerValue];
    currentBadge = currentBadge - index;
    [item setBadgeValue:currentBadge > 0?[NSString stringWithFormat:@"%ld",(long)currentBadge]:nil];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
